package com.ruoyi.loginrisk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.loginrisk.domain.SysLoginRisk;
import com.ruoyi.loginrisk.mapper.SysLoginRiskMapper;
import com.ruoyi.loginrisk.service.ISysLoginRiskService;
import com.ruoyi.loginrisk.utils.LoginRiskUtil;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SysLoginRiskServiceImpl implements ISysLoginRiskService {

    private final SysLoginRiskMapper loginRiskMapper;

    public SysLoginRiskServiceImpl(SysLoginRiskMapper loginRiskMapper) {
        this.loginRiskMapper = loginRiskMapper;
    }

    @Override
    public int insertLoginRisk(SysLoginRisk loginRisk) {
        return loginRiskMapper.insert(loginRisk);
    }

    @Override
    public List<SysLoginRisk> selectLoginRiskList(SysLoginRisk loginRisk) {
        QueryWrapper<SysLoginRisk> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(loginRisk.getUserId() != null, "user_id", loginRisk.getUserId());
        queryWrapper.eq(loginRisk.getUsername() != null && !loginRisk.getUsername().isEmpty(), "username", loginRisk.getUsername());
        queryWrapper.eq(loginRisk.getIp() != null && !loginRisk.getIp().isEmpty(), "ip", loginRisk.getIp());
        return loginRiskMapper.selectList(queryWrapper);
    }

    @Override
    public int cleanLoginRisk() {
        return loginRiskMapper.delete(new QueryWrapper<>());
    }

    @Override
    public Map<String, Object> judgeAndRecordLoginRisk(Long userId, String username, String ip, String loginLocation, String os, Date loginTime) {

        SysLoginRisk lastLoginRisk = getLastLoginInfo(userId);

        Map<String, Object> riskResult = LoginRiskUtil.judgeLoginRisk(ip, lastLoginRisk != null ? lastLoginRisk.getIp() : null, lastLoginRisk != null ? lastLoginRisk.getLoginTime() : new Date(), loginTime,lastLoginRisk != null ? lastLoginRisk.getLoginLocation() : null,loginLocation,lastLoginRisk != null ? lastLoginRisk.getOs() : null,os);

        SysLoginRisk loginRisk = new SysLoginRisk();
        loginRisk.setUserId(userId);
        loginRisk.setUsername(username);
        loginRisk.setIsRisky((Boolean) riskResult.get("isRisky"));
        loginRisk.setRiskReason((String) riskResult.get("riskReason"));
        loginRisk.setIp(ip);
        loginRisk.setLoginLocation(loginLocation);
        loginRisk.setOs(os);
        loginRisk.setLoginTime(loginTime);
        insertLoginRisk(loginRisk);

        return riskResult;
    }

    private SysLoginRisk getLastLoginInfo(Long userId) {
        QueryWrapper<SysLoginRisk> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.orderByDesc("login_time");
        queryWrapper.last("LIMIT 1");
        return loginRiskMapper.selectOne(queryWrapper);
    }

}